<!-- 物料设置->仓库设置 -->
<template>
  <div class="content-wrapper a-base-container">
    <div class="business-big-box" style="margin: 2px 8px">
      <div class="btn-wrapper clearfix">
        <a-row class="text-center clearfix">
          <a-col :xs="24" :sm="24" :md="24" :lg="16" :xl="12">
            <a-col :span="2" v-if="permissions.includes('warehouse:add')">
              <div class="btns" @click="add">
                <a-icon class="btns-icon" type="file-add" />
                <div class="btns-text">新增</div>
              </div>
            </a-col>
            <a-col :span="2" v-if="permissions.includes('warehouse:edit')">
              <div class="btns" @click="edit">
                <a-icon class="btns-icon" type="edit" />
                <div class="btns-text">修改</div>
              </div>
            </a-col>
            <a-col :span="2" v-if="permissions.includes('warehouse:delete')">
              <div class="btns" @click="remove">
                <a-icon class="btns-icon" type="delete" />
                <div class="btns-text">删除</div>
              </div>
            </a-col>
          </a-col>
        </a-row>
      </div>
      <div class="resize-table-container">
        <a-table
          :row-selection="{
            selectedRowKeys: selectedKeys,
            onChange: selection,
          }"
          :columns="houseTable.columns"
          :components="detailComponents"
          :pagination="houseTable.page"
          :data-source="houseTable.data"
          @change="houseTable.tableChange"
          :scroll="{ x: 1300, y: 0 }"
          :loading="loading"
          id="warehouse_tb"
          bordered
        >
        </a-table>
      </div>

      <drag-modal
        title="仓库编辑"
        :visible="isModalShow"
        centered
        width="900px"
        @cancel="
          () => {
            isModalShow = false;
          }
        "
      >
        <a-form
          class="ant-advanced-search-form"
          :form="form"
          :label-col="{ span: 7 }"
          :wrapper-col="{ span: 24 }"
          @submit="save"
        >
          <a-row :gutter="24">
            <a-col :span="10">
              <a-form-item
                label="编码规则"
                style="color: red; font-family: SimSun, sans-serif"
              >
                {{ ruleCode }}
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="10">
              <a-form-item label="仓库编码">
                <a-input
                  v-decorator="[
                    'whCode',
                    {
                      rules: [{ required: true, message: '仓库编码不能为空' }],
                    },
                  ]"
                  placeholder="请输入仓库编码"
                />
              </a-form-item>
            </a-col>
            <a-col :span="10" :push="2">
              <a-form-item label="仓库名称">
                <a-input
                  v-decorator="[
                    'whName',
                    {
                      rules: [{ required: true, message: '仓库名称不能为空' }],
                    },
                  ]"
                  placeholder="请输入仓库名称"
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="10">
              <a-form-item label="仓库类型">
                <a-select
                  v-decorator="[
                    'whClass',
                    { rules: [{ required: false, message: '' }] },
                  ]"
                  placeholder="请选择仓库类型"
                >
                  <a-select-option :value="1">普通仓</a-select-option>
                  <a-select-option :value="2">现场仓</a-select-option>
                  <a-select-option :value="3">委外仓</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="10" :push="2">
              <a-form-item label="负责部门">
                <input-group-search
                  modalTitle="选择部门"
                  rightStyle="width: 320px;margin-top:-45px;"
                  treeType="office"
                  :valueTitle.sync="ediItem.whDepartment"
                  v-model="ediItem.whDepartmentId"
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="10">
              <a-form-item label="负责人">
                <input-group-search
                  modalTitle="选择负责人"
                  rightStyle="width: 320px;margin-top:-45px;"
                  treeType="officeUser"
                  :valueTitle.sync="ediItem.whPerson"
                  v-model="ediItem.whPersonId"
                />
              </a-form-item>
            </a-col>
            <a-col :span="10" :push="2">
              <a-form-item label="库管员">
                <a-input
                  read-only
                  @click="
                    () => {
                      this.isUserModalShow = true;
                    }
                  "
                  v-decorator="[
                    'whKeeperName',
                    { rules: [{ required: true, message: '库管员不能为空' }] },
                  ]"
                  placeholder="请选择库管员"
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="10">
              <a-form-item label="联系电话">
                <a-input
                  v-decorator="[
                    'whTelephone',
                    {
                      rules: [{ required: false, message: '联系电话不能为空' }],
                    },
                  ]"
                  placeholder="请输入联系电话"
                />
              </a-form-item>
            </a-col>
            <a-col :span="10" :push="2">
              <a-form-item label="货位管理">
                <!-- <a-radio-group v-decorator="['storageBin', {rules: [{ required: true, message: '货位管理' }]}]">
                                    <a-radio :value="true">是</a-radio>
                                    <a-radio :value="false">否</a-radio>
                                </a-radio-group> -->
                <a-checkbox
                  :checked="ediItem.storageBin"
                  :disabled="ediItem.id"
                  @change="storageBinChange"
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="20" :pull="3">
              <a-form-item label="仓库地址">
                <a-textarea
                  placeholder="请输入地址"
                  :rows="2"
                  v-decorator="[
                    'whAddress',
                    { rules: [{ required: false, message: '' }] },
                  ]"
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="20" :pull="3">
              <a-form-item label="备注">
                <a-textarea
                  placeholder="请输入备注"
                  :rows="3"
                  v-decorator="[
                    'remarks',
                    { rules: [{ required: false, message: '' }] },
                  ]"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
        <template slot="footer">
          <div>
            <a-button
              type="primary"
              @click="save"
              v-if="permissions.includes('warehouse:save')"
              >保存</a-button
            >
            <a-button
              @click="
                () => {
                  isModalShow = false;
                }
              "
              class="margin-left-10"
              >取消</a-button
            >
          </div>
        </template>
      </drag-modal>
      <drag-modal
        title="用户选择"
        :visible="isUserModalShow"
        centered
        width="320px"
        @cancel="
          () => {
            isUserModalShow = false;
          }
        "
      >
        <div style="height: 400px; overflow-y: scroll">
          <a-input-search
            style="margin-bottom: 8px"
            placeholder="输入用户名称"
            @change="onChange"
          />
          <div v-show="treeAShow">
            <a-tree
              v-model="checkedUserKeys"
              :tree-data="userSearchData"
              :show-icon="true"
              :expanded-keys="expandedUserKeys"
              :defaultExpandAll="true"
              checkable
              @check="treeUserCheck"
            >
              <a-icon slot="user" type="user" />
            </a-tree>
          </div>
          <div v-show="treeBShow">
            <a-tree
              v-model="checkedUserKeys"
              :tree-data="userAllData"
              :show-icon="true"
              checkable
              :defaultExpandAll="true"
              @check="treeUserCheck"
            >
              <a-icon slot="user" type="user" />
            </a-tree>
          </div>
        </div>
        <template slot="footer">
          <div>
            <a-button
              type="primary"
              html-type="submit"
              @click="
                () => {
                  this.isUserModalShow = false;
                }
              "
              >确定</a-button
            >
            <a-button
              :style="{ marginLeft: '8px' }"
              @click="
                () => {
                  this.isUserModalShow = false;
                }
              "
              >关闭</a-button
            >
          </div>
        </template>
      </drag-modal>
    </div>
  </div>
</template>
<script>
const data = [];
import { mapState } from "vuex";
import { getAction, postAction } from "@/api/manage";
import { saveWarehouse, deleteWarehouse } from "@/api/inventory/warehouse";
import { getDetail } from "@/api/erp/erpGradeRule"; // 编码规则
import table from "@/mixins/table";
import { TreeDataOffice } from "@/api/office";
import { officeUserListToTree, searchInTreeData } from "@/utils/tree";
import { Controlwidth } from "@/utils/antTableComponents";
let options = [];
export default {
  mixins: [table],
  data() {
    return {
      ruleCode: 0, //仓库编码
      tabKey: "houseTable",
      loading: false,
      isModalShow: false,
      isUserModalShow: false,
      selectedUserKeys: [], //用户选择key
      selectedUserName: "", //用户tree选择name
      userAllData: [], //所有用户tree数据
      expandedUserKeys: [], //用户tree展开keys
      userSearchData: [], //用户tree搜索数据
      treeAShow: false, //搜索用户tree
      treeBShow: true, //用户tree
      checkedUserKeys: [],
      selectedKeys: [],
      selectedData: [],
      selectedIds: "",
      form: this.$form.createForm(this, { name: "advanced_search" }),
      ediItem: {
        whDepartment: "",
        whDepartmentId: null,
      },
      houseTable: this.tableInit({
        data,
        columns: [
          {
            title: "仓库编码",
            width: 120,
            dataIndex: "whCode",
            key: "whCode",
          },
          {
            title: "仓库名称",
            dataIndex: "whName",
            width: 120,
            key: "whName",
            ellipsis: true,
          },
          {
            title: "仓库类型",
            dataIndex: "whClass",
            width: 120,
            customRender: (text) => {
              return (
                <span>
                  {text == 1
                    ? "普通仓"
                    : text == 2
                    ? "现场仓"
                    : text == 3
                    ? "委外仓"
                    : ""}
                </span>
              );
            },
          },
          {
            title: "货位管理",
            dataIndex: "storageBin",
            width: 120,
            customRender: (text) => {
              return <span>{text ? "是" : "否"}</span>;
            },
          },
          { title: "库管员", dataIndex: "whKeeperName", width: 120 },
          { title: "负责人", dataIndex: "whPerson", width: 120 },
          { title: "负责部门", dataIndex: "whDepartment", width: 120 },
          { title: "联系电话", dataIndex: "whTelephone", width: 120 },
          //   { title: "手机", dataIndex: "whMobile" },
          { title: "地址", width: 200, dataIndex: "whAddress", ellipsis: true },
          { title: "备注", dataIndex: "remarks", width: 120, ellipsis: true },
          {
            title: "状态",
            dataIndex: "status",
            width: 200,
            customRender: (text) => {
              return (
                <a-tag
                  color={text == 0 ? "green" : text == 1 ? "red" : "yellow"}
                >
                  {text == 0 ? "正常" : text == 1 ? "删除" : "停用"}
                </a-tag>
              );
            },
          },
        ],
        onTablechage: () => {
          this.loadHouseData();
        },
      }),
    };
  },
  created() {
    this.reload();
    this.getCodeDetail();
  },
  updated() {
    Controlwidth("warehouse_tb", 50);
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.user.info,
      permissions: (state) => state.user.permissions,
    }),
  },
  mounted() {
    TreeDataOffice({ isLoadUser: 2 }).then((response) => {
      const { data } = response;
      const childrenNav = [];
      officeUserListToTree(data, childrenNav, "0");
      this.userAllData = childrenNav;
      this.userSearchData = childrenNav;
    });
  },
  methods: {
    //获取编码规则(仓库编码)
    getCodeDetail() {
      getDetail({ code: "warehouse" }).then((res) => {
        if (res.code == 200) {
          let code = res.data.codingRule;
          console.log("code", code);
          this.ruleCode = this.codeStyle(code);
          //this.houseTable.formColumns[0].help = `编码规则：${this.ruleCode}`;
        }
      });
    },
    //处理编码规则样式
    codeStyle(code) {
      let codeText = "";
      for (let i = 0; i < code.length; i++) {
        let codeNum = code.substring(i, i + 1);
        for (let index = 0; index < codeNum; index++) {
          codeText += "*";
        }
        codeText += " ";
      }
      return codeText;
    },
    //新增
    add() {
      this.isModalShow = true;
      this.form = this.$form.createForm(this, {});
      this.ediItem = { storageBin: false };
      this.checkedUserKeys = [];
      this.selectedKeys = [];
    },
    //编辑
    edit() {
      if (this.selectedKeys.length != 1) {
        this.$message.warning("请选择一条数据");
        return;
      }

      let data = JSON.parse(JSON.stringify(this.selectedData));
      this.ediItem = data;
      this.form = this.$form.createForm(this, {
        mapPropsToFields: () => {
          return {
            whCode: this.$form.createFormField({ value: data.whCode }),
            whName: this.$form.createFormField({ value: data.whName }),
            whClass: this.$form.createFormField({ value: data.whClass }),
            whTelephone: this.$form.createFormField({
              value: data.whTelephone,
            }),
            whAddress: this.$form.createFormField({ value: data.whAddress }),
            remarks: this.$form.createFormField({ value: data.remarks }),
            whKeeperName: this.$form.createFormField({
              value: data.whKeeperName,
            }),
          };
        },
      });
      if (data.whKeeper != null && data.whKeeper.length > 0) {
        let userKeys = data.whKeeper.split(",");
        this.checkedUserKeys = [];
        for (let i = 0; i < userKeys.length; i++) {
          this.checkedUserKeys.push(userKeys[i] + "_user");
        }
      }
      this.isModalShow = true;
    },
    //保存仓库
    save(e) {
      e.preventDefault();
      this.form.validateFields((err, values) => {
        if (!err) {
          values.whDepartment = this.ediItem.whDepartment;
          values.whDepartmentId = this.ediItem.whDepartmentId;
          values.whKeeper = this.ediItem.whKeeper;
          values.whKeeperName = this.ediItem.whKeeperName;
          values.whPerson = this.ediItem.whPerson;
          values.whPersonId = this.ediItem.whPersonId;
          values.id = this.ediItem.id;
          values.storageBin = this.ediItem.storageBin;
          saveWarehouse(values).then((res) => {
            if (res.code == 200) {
              this.$message.success("保存成功");
              this.isModalShow = false;
              this.selectedKeys = [];
              this.loadHouseData();
            } else {
              // this.$message.warning(res.message);
            }
          });
        }
      });
    },
    remove() {
      if (this.selectedKeys.length != 1) {
        this.$message.warning("请选择一条数据");
        return;
      }

      let _this = this;
      this.$confirm({
        title: "确认",
        content: "您确定要删除吗，删除后数据不能恢复？",
        onOk() {
          postAction("/in/warehouse/delete", _this.selectedIds).then((res) => {
            console.log(res);
            if (res.code == 200) {
              _this.loadHouseData();
              _this.selectedKeys = [];
              _this.$message.success("删除成功");
            } else {
              // _this.$message.warning(res.message);
            }
          });
        },
        onCancel() {},
      });
    },
    reload() {
      this.loadHouseData();
      // this.loadGoodsData();
    },
    loadHouseData(arg) {
      const { pageSize, current } = this.houseTable.page;
      let params = { size: pageSize, current: current };
      console.log(params);
      this.loading = true;
      getAction("/in/warehouse/pageList", params).then((res) => {
        console.log(res);
        if (res.code == 200) {
          this.houseTable.data = res.data.records;
          this.houseTable.page.total = res.data.total;
        } else {
          // this.$message.warning(res.message);
        }
        this.loading = false;
      });
    },
    treeUserCheck(keys, info) {
      console.log(keys, info);
      //共享人tree check事件
      this.ediItem.whKeeper = "";
      this.ediItem.whKeeperName = "";
      if (info.checkedNodes.length > 0) {
        for (let i = 0; i < info.checkedNodes.length; i++) {
          const id = info.checkedNodes[i].data.props.id;
          const name = info.checkedNodes[i].data.props.name;
          if (id.indexOf("user") != -1) {
            this.ediItem.whKeeperName += name + ",";
            this.ediItem.whKeeper += id.split("_")[0] + ",";
          }
        }
        this.ediItem.whKeeperName = this.ediItem.whKeeperName.slice(
          0,
          this.ediItem.whKeeperName.length - 1
        );
        this.ediItem.whKeeper = this.ediItem.whKeeper.slice(
          0,
          this.ediItem.whKeeper.length - 1
        );
        this.form.setFieldsValue({
          whKeeper: this.ediItem.whKeeper,
          whKeeperName: this.ediItem.whKeeperName,
        });
      } else {
        this.ediItem.whKeeperName = null;
        this.form.setFieldsValue({
          whKeeper: null,
          whKeeperName: null,
        });
      }
    },
    //用户搜索
    onChange(e) {
      const value = e.target.value;
      console.log(value);
      if (value) {
        this.treeAShow = true;
        this.treeBShow = false;
        const keys = [];
        const treeData = searchInTreeData(
          keys,
          this.userAllData,
          "title",
          value
        );
        this.userSearchData = treeData;
        this.expandedUserKeys = keys;
      } else {
        this.treeAShow = false;
        this.treeBShow = true;
        //this.areaTreeData = treeAreaData;
        this.expandedUserKeys = [];
      }
    },
    selection(keys, row) {
      this.selectedKeys = [];
      this.selectedKeys = keys;
      this.selectedData = row[0];
      const ids = new Array();
      row.forEach(function (val) {
        ids.push(val.id);
      });
      this.selectedIds = ids;
      console.log("rowKeys", this.selectedKeys);
    },
    storageBinChange(e) {
      this.ediItem.storageBin = e.target.checked;
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep {
  .ant-tabs,
  .ant-tabs-content,
  .ant-tabs-tabpane {
    display: flex;
    flex-direction: column;
    flex-grow: 1;
    height: 100%;
  }
  .houseTablex td {
    cursor: pointer;
  }
}
.goods {
  display: flex;
  justify-content: space-between;
}
.goodsTable {
  display: flex;
  flex-grow: 1;
  flex-wrap: wrap;
}

.table-box {
  display: flex;
  flex-grow: 1;
  flex-direction: column;
  height: calc(100% - 60px);
  border: 1px solid #cacaca;
}
.ant-modal {
  width: 500px;
}
.form-inline label {
  justify-content: left !important;
}
.form-inline > .col {
  margin-bottom: 1.5rem !important;
}
.icons-list >>> .anticon {
  margin-right: 8px;
  font-size: 16px;
}
.ant-advanced-search-form {
  padding: 24px;
  background: #fbfbfb;
}

.ant-advanced-search-form .ant-form-item {
  display: flex;
  margin-bottom: 0px !important;
}

.ant-advanced-search-form .ant-form-item-control-wrapper {
  flex: 1;
}
</style>
<style lang="less">
@import "~@/style/setting/business.less";
</style>